#include "bar.h"
#include "ui_bar.h"
#include <QBarSet>
#include <QBarSeries>
#include <QBarCategoryAxis>
#include <QAxObject>

Bar::Bar(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Bar)
{
    ui->setupUi(this);
    setWindowTitle("柱状图");
    setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    connect(ui->back,&QPushButton::clicked,[=](){
        emit back();
    });
    ui->xname->setPlaceholderText("请输入X轴名称");
    ui->yname->setPlaceholderText("请输入Y轴名称");

    //初始化生成柱状图的表格
    QStringList BarChartHeader;
    BarChartHeader << "系列 1" << "系列 2" << "系列 3";
    QStringList BarChartIndex;
    BarChartIndex << "类别 1" << "类别 2" << "类别 3" << "类别 4";
    //设置表格的列数和行数
    ui->tableWidget->setColumnCount(4);
    ui->tableWidget->setRowCount(5);

    //放置初始化信息
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("输入图表标题"));
    for (int row = 0; row < BarChartHeader.size(); ++row)
        ui->tableWidget->setItem(0, row+1, new QTableWidgetItem(BarChartHeader.at(row)));
    for (int column = 0; column < BarChartIndex.size(); ++column)
        ui->tableWidget->setItem(column+1, 0, new QTableWidgetItem(BarChartIndex.at(column)));

    //美化表格
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//将水平表头的列宽模式设置为自适应模式
    ui->tableWidget->horizontalHeader()->setVisible(false);//隐藏水平表头
    ui->tableWidget->verticalHeader()->setVisible(false);//隐藏垂直表头

    ui->tableWidget->setEditTriggers(QAbstractItemView::CurrentChanged);//只有当当前单元格被选中时，才能进入编辑模式
    ui->tableWidget->setAlternatingRowColors(true);//设置表格的交替行颜色
}

Bar::~Bar()
{
    delete ui;
}

void Bar::on_create_clicked()
{
    //处理数据
    int colCount = ui->tableWidget->columnCount();
    int rowCount = ui->tableWidget->rowCount();

    for(int i=0;i<rowCount;i++)
        for(int j=0;j<colCount;j++){
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item==nullptr)
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
        }

    //系列数据
    QStringList barseriesData;
    double numData[colCount - 1][rowCount - 1];//储存用户输入的数据
    for (int col = 1; col < colCount; col++) {
        barseriesData << ui->tableWidget->item(0, col)->text();//命名信息
        for (int row = 1; row < rowCount; row++) {
                numData[col - 1][row - 1] = ui->tableWidget->item(row, col)->text().toDouble();//数据
        }
    }

    //类别数据
    QStringList barcategoryData;
    for (int row = 1; row < rowCount; row++)
        barcategoryData << ui->tableWidget->item(row, 0)->text();

    QBarSeries *series = new QBarSeries();//用于显示一个柱状图

    //添加每一大类里面小类别的信息
    for (int i = 0; i < barseriesData.size(); i++) {
        QBarSet *set = new QBarSet(barseriesData.at(i));//柱子对象,获取名称
        for (int j = 0; j < barcategoryData.size(); j++) {
            *set << numData[i][j];//获取数据
        }
        series->append(set);//根据数据系列的值自动绘制相应的柱子，并将它们放置在正确的类别下，最终形成一个柱状图
    }

    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle(ui->tableWidget->item(0, 0)->text());//设置标题
    chart->setTitleFont(QFont("微软雅黑"));
    chart->setAnimationOptions(QChart::SeriesAnimations);//产生动画效果

    QBarCategoryAxis *axisX = new QBarCategoryAxis();//x轴
    axisX->append(barcategoryData);//将大类别名字添加到轴上，否则默认1、2、3、4.....
    chart->addAxis(axisX, Qt::AlignBottom);//名字显示在图表的底部
    series->attachAxis(axisX);//确保每个柱子都放在正确的位置
    axisX->setTitleText(ui->xname->text());//设置名称

    QValueAxis *axisY = new QValueAxis();//y轴（数值轴）
    chart->addAxis(axisY, Qt::AlignLeft);//左对齐
    series->attachAxis(axisY);
    series->setLabelsVisible(true);//每个柱子添加数值
    series->setLabelsFormat("@value");
    series->setLabelsPosition(QAbstractBarSeries::LabelsInsideEnd);
    axisY->setTitleText(ui->yname->text());//设置名称

    //标识图表中的不同数据系列
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignTop);

    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);//抗锯齿

    QMainWindow *window = new QMainWindow();
    window->setCentralWidget(chartView);
    window->resize(1000, 800);
    window->setWindowTitle("基本柱状图");
    window->setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    window->show();
}

void Bar::on_addkinds_clicked()
{
    int count = ui->tableWidget->rowCount();
    ui->tableWidget->setRowCount(count + 1);
    ui->tableWidget->setItem(count, 0, new QTableWidgetItem("类别 " + QString::number(count)));
}

void Bar::on_add_clicked()
{
    int count = ui->tableWidget->columnCount();
    ui->tableWidget->setColumnCount(count + 1);
    ui->tableWidget->setItem(0, count, new QTableWidgetItem("系列 " + QString::number(count)));
}

void Bar::on_delete_2_clicked()
{
    int count = ui->tableWidget->columnCount();
    if (count > 2)
        ui->tableWidget->removeColumn(count - 1);
    else
        QMessageBox::warning(this, "警告", "至少要有一列");
}

void Bar::on_deletekinds_clicked()
{
    int count = ui->tableWidget->rowCount();
    if (count > 2)
        ui->tableWidget->removeRow(count - 1);
    else
        QMessageBox::warning(this, "警告", "至少要有一行");
}

void Bar::on_clear_clicked()//清空操作
{
    int rowcount=ui->tableWidget->rowCount();
    int columncount=ui->tableWidget->columnCount();
    for(int i=0;i<rowcount;i++)
        for(int j=0;j<columncount;j++){
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item==nullptr)
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
            else
                ui->tableWidget->item(i,j)->setText("");
        }
    ui->tableWidget->item(0,0)->setText("输入图表标题");
    for(int i=1;i<rowcount;i++)
        ui->tableWidget->item(i,0)->setText("类别 " + QString::number(i));
    for(int i=1;i<columncount;i++)
        ui->tableWidget->item(0,i)->setText("系列 " + QString::number(i));
}

void Bar::on_pushButton_clicked()
{
    QString fileName=QFileDialog::getOpenFileName(this,"读取","C:\\Users","(*.xlsx)");
    if(fileName.isEmpty())
        return;
    fileName=QDir::toNativeSeparators(fileName);

    QAxObject* excel = new QAxObject("Excel.Application", this);
    QAxObject* workbooks = excel->querySubObject("Workbooks");
    QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", fileName);
    QAxObject* sheets = workbook->querySubObject("Sheets");
    QAxObject* sheet = sheets->querySubObject("Item(int)", 1); // 第一个工作表
    QAxObject* usedRange = sheet->querySubObject("UsedRange");
    QAxObject* rows = usedRange->querySubObject("Rows");
    QAxObject* columns = usedRange->querySubObject("Columns");

    int rowCount = rows->property("Count").toInt();
    int columnCount = columns->property("Count").toInt();

    ui->tableWidget->setRowCount(rowCount+1);
    ui->tableWidget->setColumnCount(columnCount+1);

    for(int i=0;i<ui->tableWidget->rowCount();i++)
        for(int j=0;j<ui->tableWidget->columnCount();j++){
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item==nullptr)
                ui->tableWidget->setItem(i, j, new QTableWidgetItem(""));
        }

    for (int row = 1; row <= rowCount; ++row) {
        for (int column = 1; column <= columnCount; ++column) {
            QAxObject* cell = sheet->querySubObject("Cells(int,int)", row, column);
            QString value = cell->property("Value").toString();
            ui->tableWidget->item(row, column)->setText(value);
        }
    }

    workbook->dynamicCall("Close()");
    excel->dynamicCall("Quit()");
}
